package cn.huiyunche.base.service.framework.utils;

import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: BaiDuMapUtils
 * @Description: 百度地图工具类
 * @author: Aaron
 * @date: 2016年10月8日 下午3:39:51
 */
public class BaiDuMapUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaiDuMapUtils.class);

    //张强key
//	private static final String AK = "mo13TvMcURS2kjsiCVtIWVRTAFOCoxX4";

    //公司key
    private static final String AK = "Sfp9cEKmk0p7BzUl1NwQPCIgYrh1m83L";

    private static Pattern gps_pattern = Pattern.compile("\"lng\":(\\d+\\.\\d+),\"lat\":(\\d+\\.\\d+)");

    private static Pattern distance_pattern = Pattern.compile("\"distance\":\\{\"text\":\"\\d+\\.\\d+\\u516c\\u91cc\",\"value\":\\d+\\}|\"distance\":\\{\"text\":\"\\d+\\u516c\\u91cc\",\"value\":\\d+\\}");

    /**
     * 地址转经纬度
     *
     * @param address 地址
     * @return
     * @throws BusinessException
     */
    public static double[] addressToGPS(String address) throws Exception {
        String addressEncode = address;
        try {
            addressEncode = URLEncoder.encode(address, CharEncoding.UTF_8);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("addressToGPS encode error: {}", e);
            throw new BusinessException("地址编码错误");
        }
        LOGGER.info("addressToGPS addressStr:{} encoded: {}", address, addressEncode);
        String url = String.format("http://api.map.baidu.com/geocoder/v2/?output=json&address=%s&ak=%s", addressEncode, AK);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            LOGGER.error("addressToGPS URL error: {}", e);
            throw new BusinessException("地址转GPS错误");
        }
        try {
            InputStreamReader insr = null;
            BufferedReader br = null;
            httpsConn = myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = "";
                String line = null;
                while ((line = br.readLine()) != null) {
                    data += line;
                }
                Matcher matcher = gps_pattern.matcher(data);
                if (matcher.find() && matcher.groupCount() == 2) {
                    double[] gps = new double[2];
                    gps[0] = Double.valueOf(matcher.group(1));
                    gps[1] = Double.valueOf(matcher.group(2));
                    return gps;
                }
            }
        } catch (Exception e) {
            LOGGER.error("addressToGPS get error: {}", e);
            throw new BusinessException("获取地址经纬度错误");
        }
        return null;
    }

    public static String distance(String urlStr) {
        if (StringUtils.isBlank(urlStr)) {
            return null;
        }
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(urlStr);
        } catch (MalformedURLException e) {
            LOGGER.error("distance URL error: {}", e);
            throw new BusinessException("获取地址经纬度错误");
        }
        try {
            InputStreamReader insr = null;
            BufferedReader br = null;
            httpsConn = myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = "";
                String line = null;
                while ((line = br.readLine()) != null) {
                    data += line;
                }
                Matcher matcher = distance_pattern.matcher(data);
                if (matcher.find()) {
                    return matcher.group(0);
                }
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("distance get error: {}", e);
            throw new BusinessException("获取两地之间距离错误");
        }
        return null;
    }


    /**
     * 获取两地之间驾车导航距离
     *
     * @param origins      出发点（经度和纬度用","分隔）
     * @param destinations 目的地 （经度和纬度用","分隔）
     * @param output       输出格式，默认JSON
     * @return
     */
    public static String distance(String origins, String destinations, String output) {
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?origins=%s&destinations=%s&output=%s&ak=%s", origins, destinations, output.toLowerCase(), AK);
        return distance(url);
    }

    /**
     * @param origins
     * @param destinations
     * @param output
     * @param tactics      只对驾车算路(driving)生效。 
     *                     可选值：10 不走高速；11 最短时间；12 最短路径；13 最短 距离(不考虑路况); 
     *                     其中10-12 都考虑实时路况，若希望计算最可靠的最短路线距离，建议使用不考虑实时路况的默认值13。
     * @return
     */
    public static String distance(String origins, String destinations, String output, String tactics) {
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?origins=%s&destinations=%s&output=%s&ak=%s&tactics=%s", origins, destinations, output.toLowerCase(), AK, tactics);
        return distance(url);
    }


}
